package com.example.myblog.common;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * 加密密码工具
 * 加盐算法
 * */
public class PasswordTools {
    /*
     *
     * 加密
     */
    public static String encrypt(String password){
        //产生盐值
        String salt= UUID.randomUUID().toString().replace("-","");
        String finalPassword= DigestUtils.md5DigestAsHex((salt+password).getBytes(StandardCharsets.UTF_8));
        //使用（盐值+明文密码）的到返回的加密密码
        String dbPassword=salt+"$"+finalPassword;
        return  dbPassword;

    }
    /*
     *
     * 解密
     *
     */
    public static boolean decrypt(String password,String dbPassword){
        boolean result=false;
        if (StringUtils.hasLength(password)&&StringUtils.hasLength(dbPassword)
        &&dbPassword.length()==65&&dbPassword.contains("$")){
            String[] passwordArr=dbPassword.split("\\$");
            String salt=passwordArr[0];
            String checkPassword=encrypt(password,salt);
            if (dbPassword.equals(checkPassword)){
                result=true;
            }
        }
        return result;
    }
    public static String encrypt(String password,String salt){
        String finalPassword= DigestUtils.md5DigestAsHex((salt+password).getBytes(StandardCharsets.UTF_8));
        //使用（盐值+明文密码）的到返回的加密密码
        String dbPassword=salt+"$"+finalPassword;
        return  dbPassword;

    }
    public static void main(String[] args) {
        String password="123456";
        System.out.println(PasswordTools.encrypt(password));
        System.out.println(PasswordTools.encrypt(password));
        System.out.println(PasswordTools.encrypt(password));
        System.out.println(PasswordTools.encrypt(password));
    }
}
